#include <iostream>
#include <fstream>
#include <list>
#include <sstream>
#include <windows.h>
#include <bitset>

using namespace::std;

LARGE_INTEGER t1, t2, tc;

bitset<9000000> x[1756];
bitset<9000> y[1756];

int main()
{
    ofstream outfile;
    outfile.open("output.txt", ios::out);
    ifstream index("ExpIndex",ios::binary);
    int t_count;
    int s_count = 0;
    while(index.read((char*) &t_count, 4))
    {
        int tmp;
        for(int i = 0;i < t_count;i++)
        {
            index.read((char*) &tmp, 4);
            if(tmp >= 0 && tmp < 9000000)
            {
                x[s_count][tmp] = 1;
            }
        }
        s_count++;
    }
    for(int o = 0;o < 1756;o++)
    {
        for(int i = 0;i < 9000000;i+=1000)
        {
            int flag = 0;
            for(int j = i;j < i + 1000;j++)
            {
                if(x[o][j] == 1)
                {
                    flag = 1;
                    break;
                }
            }
            if(flag == 1)
            {
                y[o][i/1000] = 1;
            }
        }
    }
    index.close();
    ifstream query("ExpQuery",ios::in);
    string str;
    while(getline(query,str))
    {
        stringstream s(str);
        int z[6];
        int n = 0;
        string ch;
        while(s >> ch)
        {
            int t = 0;
            for(int i = 0;i < ch.length();i++)
            {
                t = t*10 + ((int)ch[i] - (int)'0');
            }
            z[n] = t;
            n++;
        }
        QueryPerformanceFrequency(&tc);
        QueryPerformanceCounter(&t1);
        bitset<9000000> tp(0);
        for(int i = 1;i < n;i++)
        {
            for(int j = 0;j < 9000;j++)
            {
                if(y[z[i]][j] == 1 && y[z[0]][j] == 1)
                {
                    for(int o = j * 1000;o < (j + 1) * 1000;o++)
                    {
                        if(x[z[i]][o] == 1 && x[z[0]][o] == 1)
                        {
                            tp[o] = 1;
                        }
                    }
                }
            }
        }
        QueryPerformanceCounter(&t2);
        outfile<<((t2.QuadPart - t1.QuadPart)*1000.0 / tc.QuadPart)<<"ms"<<endl;
    }
    query.close();
    system("pause");
    return 0;
}
